package com.lzq.framework.core.interceptor;


import com.lzq.framework.core.annotation.Token;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;


/**
 * 数据重复提交拦截器
 * 为什么不是spring aop呢 因为springaop是切面 不能阻断方法的执行
 * @author 刘赵强
 * @version V1.0
 * @date 2015年5月20日 上午11:33:54
 * <B>注意：还需要spirng-tokenInterceptor.xml的配置</B>
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * 重定向地址
     */
    private String redirecturl;

    public String getRedirecturl() {
        return redirecturl;
    }

    public void setRedirecturl(String redirecturl) {
        this.redirecturl = redirecturl;
    }

    /**
     * token
     */
    private static final String TOKEN = "token";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {
                    request.getSession(true).setAttribute(TOKEN, UUID.randomUUID().toString());
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        response.sendRedirect(request.getContextPath() + redirecturl);
                        return false;
                    }
                    request.getSession().removeAttribute(TOKEN);
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    /**
     * 根据token值判断是不是重复提交数据
     *
     * @param request HttpServletRequest
     * @return true 重复提交 false 非重复提交
     * @author lihao
     * @date 2015年5月21日 下午3:21:59
     */
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute(TOKEN);
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter(TOKEN);
        if (clinetToken == null) {
            return true;
        }
        return !serverToken.equals(clinetToken);
    }
}

